package com.example.feature.demo.service;


import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * RateLimiterService
 *
 * @author zhouxianfeng
 * @date 2021-5-10
 */
@Service
public class RateLimiterService {

    private static final Logger LOGGER = LoggerFactory.getLogger(RateLimiterService.class);

    private static final String REDISSON_RATE_LIMITER = "redisson_rate_limiter:";
    private static final String TwoPointPolyline = "TwoPointPolyline";

    @Autowired
    private RedissonClient redisson;

    public void sendMsg(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            RRateLimiter rateLimiter =
                    redisson.getRateLimiter(REDISSON_RATE_LIMITER + TwoPointPolyline);
            //每10秒产生1个令牌
            rateLimiter.trySetRate(RateType.OVERALL, 1, 10,
                    RateIntervalUnit.SECONDS);
            if (rateLimiter.tryAcquire(1, 10, TimeUnit.SECONDS)) {
                LOGGER.info("向手机:{}发送短信", phone);
            }
        }
    }
}